<template>
	<view class="agreement_signing">
		<scroll-view :scroll-y="scroll_y">
			<view class="img">
				<image class="xieyiimg" v-for="(item,index) in imgList" :key="index" :src="item" mode="widthFix">
				</image>
				<image class="xieyiimg" :src="base_img" mode="widthFix"></image>
			</view>
			<p style="color:red;text-align: center;padding:30rpx 0;">请横屏签名并点击确认按钮</p>
			<view class="container">
				<view class="sign-box">
					<canvas class="mycanvas" :style="{ width: width + 'px', height: height + 'px' }"
						canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove"
						@touchend="touchend"></canvas>
					<canvas canvas-id="camCacnvs" :style="{ width: height + 'px', height: width + 'px' }"
						class="canvsborder"></canvas>
				</view>
				<view class="sigh-btns">
					<button class="btn" style="background-color: red;" @tap="handleReset">重写</button>
					<button class="btn" style="background-color: #19be6b;" @tap="handleConfirm">确认</button>
				</view>
				<view class="">
					<img src="" alt="">
				</view>
			</view>
			<view class="agreement_signing_form">
				<view class="input_box">
					<p>*姓名：</p><input class="uni-input" type="text" v-model="user.user_name" placeholder="请输入姓名" />
				</view>
				<view class="input_box">
					<p>*身份证：</p><input v-model="user.id_card" class="uni-input" maxlength=18 placeholder="请输入证件号码" />
				</view>
				<view class="input_box">
					<p>*地址：</p><input class="uni-input" type="text" v-model="user.user_address" placeholder="请输入地址">
				</view>
				<view class="input_box">
					<p>*电话：</p><input class="uni-input" value="" maxlength=11 v-model="user.user_mobile" type="number"
						placeholder="请输入电话号码" />
				</view>
				<button class="agreement_signing_form_up" @click="tijiaofun()">提交</button>
			</view>
		</scroll-view>

		<uni-file-picker v-model="imageValue" fileMediatype="image" mode="grid" @select="select" @progress="progress"
			@success="success" @fail="fail" />

	</view>
</template>

<script>
	// import loginVue from '../login/login.vue';
	var x = 20;
	var y = 20;
	var tempPoint = []; //用来存放当前画纸上的轨迹点
	var id = 0;
	var type = '';
	let that;
	let canvasw;
	let canvash;
	export default {
		data() {
			return {
				ctx: '', //绘图图像
				points: [], //路径点集合,
				width: 0,
				height: 0,
				base: '',
				base_img: '',
				imgList: '',
				url: '',
				signatureFlag: false,
				//身份信息采集
				user: {
					openid: '',
					user_name: '',
					user_mobile: '',
					id_card: '',
					level: '',
					sign_pic: '',
				},
				userMobileRegular: /^1[3|4|5|6|7|8|9][0-9]{9}$/,
				idCardRegular: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
				scroll_y: false,
				imageValue:[{
					name: "file.txt",
					extname: "txt",
					url: "",
				}]
			}
		},
		mounted() {


		},

		onLoad(option) {
			that = this;
			

			this.ctx = uni.createCanvasContext('mycanvas', this); //创建绘图对象
			//设置画笔样式
			this.ctx.lineWidth = 4;
			this.ctx.lineCap = 'round';
			this.ctx.lineJoin = 'round';

			uni.getSystemInfo({
				success: function(res) {
					that.width = res.windowWidth * 0.8;
					that.height = res.windowHeight * 0.85;
				}
			});

		},

		methods: {
			select(e){
				console.log(e);
			},
			progress(e){
					console.log(e);
			},
			success(e){
					console.log(e);
			},
			stop() {
				this.scroll_y = false
			},
			move() {
				this.scroll_y = true

			},
			drow(width, height) {

				uni.canvasToTempFilePath({

					canvasId: 'mycanvas',
					success: function(res) {
						// 在H5平台下，tempFilePath 为 base64
						console.log(res.tempFilePath)
					},
					fail(err) {
						console.log(err);
					}
				})
			},
			async zuanhuan() {
				var _this = this
				const img = await uni.getImageInfo({
					src: _this.base_img,
					success(res) {
						console.log(res);
						let width = res.width
						let height = res.height
						const canvas = uni.createCanvasContext('666', _this)
						// const canvas = document.createElement('canvas')
						console.log(canvas);
						canvas.width = width
						canvas.height = height
						// const ctx = canvas.getContext('2d')
						canvas.drawImage(img, 0, 0)
						canvas.draw()
						console.log(canvas);

						_this.drow(width, height)
					}
				})

				// 	const img = new Image()
				// 	console.log(1);
				// 	img.crossOrigin = 'anonymous'
				// 	img.src = this.base_img
				// 	img.onload = () => {

				// 	 const canvas = document.createElement('canvas')
				// 	 console.log(canvas);
				// 	 canvas.width = img.width
				// 	 canvas.height = img.height
				// 	 const ctx = canvas.getContext('2d')
				// 	 console.log(img);
				// 	 ctx.drawImage(img, 0, 0)
				// 	 this.base_img = canvas.toDataURL('image/jpeg')
				// 	 console.log( this.base_img );
				// 	}
			},
			tijiaofun() {
				const _this = this

				switch (true) {
					case this.signatureFlag === false:
						this.showinteraction('请先签名', 'none');
						break;
					case this.user.user_name === '':
						this.showinteraction('请输入您的姓名', 'error');
						break
					case this.user.id_card === '' || !this.idCardRegular.test(this.user.id_card):
						this.showinteraction('请核对证件号格式是否正确', 'error');
						break;
					case this.user.user_address === '':
						this.showinteraction('请输入您的地址', 'error');
						break;
					case this.user.user_mobile === '' || !this.userMobileRegular.test(this.user.user_mobile):
						this.showinteraction('请核对手机号格式是否正确', 'error');
						break;
					default:
						uni.uploadFile({
							url: 'http://a.guaiou.pet/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=util.uploader&app=1',
							//仅为示例，非真实的接口地址
							filePath: this.base_img,
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: (res) => {
								console.log(res);
								let data = JSON.parse(res.data);
								this.user.sign_pic = data.url;
								console.log(this.user.sign_pic);
								uni.request({
									url: 'http://a.guaiou.pet/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=api.index.do_apply&app=1',
									method: 'POST',
									data: this.user,
									header: {
										'Content-Type': 'application/x-www-form-urlencoded'
									},
									success(res) {
										console.log(res);
										_this.showinteraction(res.data.message, 'none');
										if (res.data.error === 0) {
											setTimeout(() => {
												_this.goToagreement_list();
											}, 2000);
										}
									}
								})
							}
						});
				}
			},
			goToagreement_list() {
				uni.navigateTo({
					url: '/pages/agreement_list/index'
				})
			},
			showinteraction(title, icon) {
				uni.showToast({
					title,
					icon,
					duration: 2000,
					mask: true,
					success(res) {
						console.log(res);
					}
				})
			},
			//触摸开始，获取到起点
			touchstart: function(e) {
				this.stop();
				let startX = e.changedTouches[0].x;
				let startY = e.changedTouches[0].y;
				let startPoint = {
					X: startX,
					Y: startY
				};

				/* **************************************************
				    #由于uni对canvas的实现有所不同，这里需要把起点存起来
				 * **************************************************/
				this.points.push(startPoint);

				//每次触摸开始，开启新的路径
				this.ctx.beginPath();
			},

			//触摸移动，获取到路径点
			touchmove: function(e) {
				let moveX = e.changedTouches[0].x;
				let moveY = e.changedTouches[0].y;
				let movePoint = {
					X: moveX,
					Y: moveY
				};
				this.points.push(movePoint); //存点
				let len = this.points.length;
				if (len >= 2) {
					this.draw(); //绘制路径
				}
				tempPoint.push(movePoint);
			},

			// 触摸结束，将未绘制的点清空防止对后续路径产生干扰
			touchend: function() {
				this.points = [];
				this.move()
			},

			/* ***********************************************	
			#   绘制笔迹
			#   1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
			#   2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
			#   3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
			************************************************ */
			draw: function() {
				let point1 = this.points[0];
				let point2 = this.points[1];
				this.points.shift();
				this.ctx.moveTo(point1.X, point1.Y);
				this.ctx.lineTo(point2.X, point2.Y);
				this.ctx.stroke();
				this.ctx.draw(true);
			},

			handleCancel() {
				uni.navigateBack({
					delta: 1
				});
			},

			//清空画布
			handleReset: function() {
				console.log('handleReset');
				that.ctx.clearRect(0, 0, that.width, that.height);
				that.ctx.draw(true);
				tempPoint = [];

			},

			handleConfirm: function() {
				var _this = this;
				if (tempPoint.length == 0) {
					_this.signatureFlag = false;
					uni.showToast({
						title: '请先签名',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				uni.canvasToTempFilePath({
					canvasId: 'mycanvas',
					success: function(res) {
						console.log(res);
						_this.signatureFlag = true;
						// console.log(this.signatureFlag);
						let tempPath = res.tempFilePath;
						const ctx = uni.createCanvasContext('camCacnvs', that);
						if (uni.screenWidth > uni.screenHeight) {
							ctx.translate(0, 0);
							ctx.rotate(0);
						} else {
							ctx.translate(0, that.width);
							ctx.rotate((-90 * Math.PI) / 180);
						}
						ctx.drawImage(tempPath, 0, 0, that.width, that.height);
						ctx.draw();
						setTimeout(() => {
							// 保存签名图片到本地
							uni.canvasToTempFilePath({
								canvasId: 'camCacnvs',
								success: function(res) {
									// 这是签名图片文件的本地临时地址
									let path = res.tempFilePath;
									_this.base = path;
									_this.setimg();
								},
								fail: err => {
									console.log('fail', err);
								}
							});
						}, 200);
					}
				});
			},
			async setimg() {
				this.zuanhuan()
				console.log(1);
				var _this = this;

				var originalImage = new Image();
				console.log(1);
				originalImage.src = this.base_img;
				originalImage.onload = function() {
					var canvas = document.createElement('canvas');
					var context = canvas.getContext('2d');
					canvas.width = originalImage.width;
					canvas.height = originalImage.height;
					context.drawImage(originalImage, 0, 0); // 绘制原始图片
					var base64Data = _this.base;
					var image = new Image();
					image.src = base64Data;
					image.onload = function() {
						context.drawImage(image, 1500, 1190, 200, 200); // 绘制Base64图像
						var mergedImageData = canvas.toDataURL('image/png'); // 获取合成后的图像数据
						_this.base_img = mergedImageData; // 更新 base_img 数据
						console.log(mergedImageData);
						_this.user.sign_pic = mergedImageData;
						_this.showinteraction('签名完成', 'succss');
						// 更新 <image> 的 src
						// 注意：在 Vue.js/UniApp 中，使用 data 中的属性更新视图
					};
				};
			},

		}
	};
</script>

<style lang="scss">
	.img {
		width: 100%;

		.xieyiimg {
			width: 100%;
			position: relative;
		}

	}

	.sign-box {
		width: 80%;
		height: 90%;
		margin: auto;
		display: flex;
		text-align: center;
	}


	.sigh-btns {
		height: 100%;
		margin: auto;
		display: flex;
		// flex-direction: column;
		justify-content: space-around;
	}

	.btn {
		margin: 20rpx auto;
		height: 70rpx;
		line-height: 70rpx;
		width: 30%;
		color: #fff;

	}

	.mycanvas {
		// transform: rotate(90deg);
		margin: auto 0rpx;
		background-color: #ececec;
	}

	.canvsborder {
		border: 1rpx solid #333;
		position: fixed;
		top: 0;
		left: 10000rpx;
	}



	.agreement_signing_form {
		padding: 0 20rpx;
		margin: 40rpx auto 40rpx auto;
		width: 80%;

		.input_box {
			line-height: 100rpx;
			display: flex;
			align-items: center;
			margin: 10rpx 0;

			p {
				width: 140rpx;
			}

			input {
				height: 80rpx;
				border: 2rpx solid #f6f6f6;
			}

		}

		.agreement_signing_form_up {
			background-color: #19be6b;
			color: #fff;
			height: 80rpx;
			line-height: 80rpx;
		}
	}
</style>